import config from '@/config'
import storage from '@/utils/storage'
import { constant } from '@/utils/constant'
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { setStatus, setTokenAlias } from '../../utils/auth'

const baseUrl = config.baseUrl

const user = {
  state: {
    userInfo: {},
    token: getToken(),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    userId: storage.get(constant.userId),
    staffId: storage.get(constant.staffId), // 企业人员的id
    deptId: storage.get(constant.deptId),
    deptName: storage.get(constant.deptName),
    isLocked: false, // 账号锁定
    expireTime: 0 // 账号锁定倒计时
  },

  mutations: {
    SET_USER_INFO: (state, value) => {
      state.userInfo = value
    },
    SET_DEP_ID: (state, deptId) => {
      state.deptId = deptId
      storage.set(constant.deptId, deptId)
    },
    SET_DEPT_NAME: (state, deptName) => {
      state.deptName = deptName
      storage.set(constant.deptName, deptName)
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
      storage.set(constant.userId, userId)
    },
    SET_STAFFID: (state, staffId) => {
      state.staffId = staffId
      storage.set(constant.staffId, staffId)
    },
    SET_IS_LOCKED: (state, flag) => {
      state.isLocked = flag
    },
    SET_EXPIRE_TIME: (state, time) => {
      state.expireTime = time
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const platform = 1
      return new Promise((resolve, reject) => {
        login(username, password, platform)
          .then((res) => {
            // isEffective
            // true 允许登录 false 强制修改密码
            setStatus(res.isEffective)
            setTokenAlias(res.token)
            if (res.isEffective) setToken(res.token)
            commit('SET_TOKEN', res.token)
            resolve()
          })
          .catch((error) => {
            const code = error?.code || error
            let expireTime = 60
            if (code === 5001) {
              commit('SET_IS_LOCKED', true)
              commit('SET_EXPIRE_TIME', expireTime)
              const timer = setInterval(() => {
                expireTime--
                commit('SET_EXPIRE_TIME', expireTime)
                if (expireTime < 1) {
                  commit('SET_IS_LOCKED', false)
                  clearInterval(timer)
                }
              }, 1000)
            }
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.data
            const avatar =
              user == null || user.avatar == '' || user.avatar == null
                ? require('@/static/images/default_avatar_icon.png')
                : baseUrl + user.avatar
            if (res.roles && res.roles.length > 0) {
              commit('SET_ROLES', res.roles)
              commit('SET_PERMISSIONS', res.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_NAME', user.staffName)
            commit('SET_AVATAR', avatar)
            commit('SET_USERID', user.accountId)
            commit('SET_STAFFID', user.staffId)
            commit('SET_DEP_ID', user.deptId)
            commit('SET_DEPT_NAME', user.dept?.deptName)
            commit('SET_USER_INFO', user)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          resolve()
        })
      })
    }
  }
}

export default user
